package com.niuma.servlet;

import com.niuma.pojo.User;
import com.niuma.service.user.UserService;
import com.niuma.service.user.UserServiceImpl;
import com.niuma.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 一颗蛋50斤
 */
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.updatePassword(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 修改用户密码方法
     */
    void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从 Session 中获取用户的数据
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        // 从请求中获取到用户输入的旧密码
        String oldPassword = req.getParameter("oldPassword");
        // 从请求中获取到用户输入的新密码
        String newPassword = req.getParameter("newPassword");
        boolean flag = false;

        // 如果用户的信息、获取的旧密码及新密码不为空则执行密码修改操作
        if (o != null && oldPassword != null && newPassword != null) {
            // 创建业务层 UserService 对象
            UserService userService = new UserServiceImpl();
            // 调用业务层修改密码操作
            flag = userService.updatePassword(((User) o).getUserPassword(), oldPassword, newPassword, ((User) o).getId());
        }

        if (flag) {
            /* req.setAttribute(Constants.MASSAGE, "密码修改成功，请重新登录"); */
            resp.getWriter().print("密码修改成功，请重新登录");
            // 密码修改成功，移除 Session
            req.getSession().removeAttribute(Constants.USER_SESSION);
        } else {
            /* req.setAttribute(Constants.MASSAGE, "密码修改失败，请检查输入操作且回忆旧密码是否输入正确"); */
            resp.getWriter().print("密码修改失败，请检查输入操作且回忆旧密码是否输入正确");
        }

        //req.getRequestDispatcher(req.getContextPath()+"/jsp/passwordModify.jsp").forward(req, resp);
    }
}
